package com.entrogy.controller;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.service.*;
import com.entrogy.utils.IdGenetor;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName HomeworkController
 * @Description
 * @Author luoxingjiang
 * @Date 2019/7/22 0022 上午 11:14
 * @Version 1.0
 **/
@RestController
@RequestMapping("/homework")
@Api(description = "作业发送接口")
public class HomeworkController {

    private static final Logger logger = LoggerFactory.getLogger(HomeworkController.class);

    @Autowired
    private HomeworkService homeworkService;// 作业管理

    @Autowired
    private UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private ParentService parentService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private MessageService messageService;

    //图片存放根路径
    @Value("${image.root.path}")
    private String rootPath;

    @Value("${show.image.url}")
    private String showImage;

    @ApiOperation(value = "PC端分页获取作业管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="currentPage",value = "当前页数",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "每页条数",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "classId",value = "班级id",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "courseId",value = "课程id",dataType = "Integer",paramType = "query"),
    })
    @GetMapping(value = "/getHomeworkList")
    public Msg getHomeworkList(Integer  currentPage, Integer  pageSize, Integer  classId, Integer courseId){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        String teacherId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        PageHelper.startPage(currentPage, pageSize);
        List<HomeworkEntity> homeworkList = homeworkService.listHomeworkInfo(teacherId, schoolCode, classId, courseId);
        PageInfo<HomeworkEntity> pageInfo = new PageInfo<>(homeworkList, 5);
        return Msg.success().add("pageInfo", pageInfo);
    }

    @ApiOperation(value = "作业图片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name="uid",value = "用户id",dataType = "Integer",paramType = "query",required = true),
    })
    @PostMapping(value = "/homeworkImageUpload")
    public Msg upload(MultipartFile file, String uid) {
        //返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
        //防止上传空文件导致奔溃
        if (file.isEmpty()) {
            return Msg.fail(ErrorEnum.E_101, "文件为空");
        }
        //作业图片存储路径为schoolCode=>teacherId=>homework(表示存储的是家庭作业的图片信息)=>date(创建日期)=>图片文件名
        UserEntity userEntity = userService.getUserByUid(uid);
        Integer schoolCode = userEntity.getSchoolCode();
        Date createDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(createDate);
        // 获取文件名
        String fileName = IdGenetor.genUUIDFileName() + "_" + file.getOriginalFilename();
        //logger.info("上传的文件名为：" + fileName);
        // 设置文件上传后的路径
        String imageUrl = schoolCode+ File.separator +
                uid + File.separator +
                "homework" + File.separator +
                date + File.separator +
                fileName;
        String filePath = rootPath + File.separator + schoolCode+ File.separator +
                uid + File.separator +
                "homework" + File.separator +
                date;
        //创建文件路径
        File dest = new File(filePath ,fileName);
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return Msg.success().add("imageUrl", imageUrl).add("showImage", showImage);
        } catch (Exception e) {
            return Msg.fail(ErrorEnum.E_101, "上传失败");
        }
    }

    @ApiOperation(value = "创建作业并发送")
    @PostMapping(value = "/sendHomework")
    public Msg addHomework(@ApiParam(name = "homework", value = "作业实体") @RequestBody HomeworkEntity homework){
        String teacherId;
        // 如果homework内没有teacherId,则为pc端请求
        if (homework.getTeacherId() == null){
            teacherId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }else {
            teacherId = homework.getTeacherId();
        }
        UserEntity userEntity = userService.getUserByUid(teacherId);
        String teacherName = userEntity.getName();
        Integer schoolCode = userEntity.getSchoolCode();
        // 拼接该次作业的标题，格式为2019年07月23号高2019级01班语文作业
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String date = simpleDateFormat.format(homework.getSendTime());
        String title = date + homework.getCourseName() + "作业";
        homework.setSchoolCode(schoolCode).setTeacherId(teacherId).setTeacherName(teacherName).setTitle(title);
        // 向数据库插入新增的数据记录
        Integer homeworkId = homeworkService.addHomework(homework);
        // 查询出该班级的所有学生的父母的微信的openid用于推送公众信息
//        List<String> parentOpenIds = homeworkService.listClassParentOpenId(homework.getClassId(), homework.getSchoolCode());
        List<StudentEntity> studentList = studentService.listStudentByClassId(String.valueOf(homework.getClassId()), homework.getSchoolCode());
        // 该校是否处于试运行状态
        Integer openStatus = schoolService.getSchoolOpenStatus(schoolCode);
        // 应发送的家长人数
        int totalParentCount = 0;
        // 没发送的家长人数
        int noSendParent = 0;
        List<String> sendParentOpenIdList = new ArrayList<>();
        for (StudentEntity studentEntity : studentList) {
            List<ParentVisitorEntity> studentParentList = parentService.listParentByStudentId(studentEntity.getId());
            for (ParentVisitorEntity parentVisitorEntity : studentParentList) {
                totalParentCount++;
                // 判断该学生是否开通通知服务
                if (openStatus == 0){
                    boolean studentIsPay = studentService.studentIsPay(studentEntity.getId());
                    if (!studentIsPay){
                        noSendParent++;
                        logger.info("学生=>" + studentEntity.getStudentName() + "未付费，此次作业将不会发送给家长=>" + parentVisitorEntity.getParentVisitorName());
                        continue;
                    }
                }
                PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(parentVisitorEntity.getParentVisitorPhone());
                if (null != pubCountEntity && StringUtils.isNoneBlank(pubCountEntity.getOpenid()))
                    sendParentOpenIdList.add(pubCountEntity.getOpenid());
                String schoolName = schoolService.getSchoolName(schoolCode);
                String content = homework.getTeacherName() + "老师发布了" + homework.getCourseName() + "作业，请及时查看！";
                String[] paramsWeiXin = { "",  schoolName, homework.getTeacherName(), new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(homework.getSendTime()), content, ""};
                // path参数为点击公众号消息后跳转的地址
                SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/homework/homeworklist");
            }
        }
        if (sendParentOpenIdList.size() > 0){
            boolean insertHomeworkSendRecordResult = homeworkService.insertHomeworkSendRecord(homeworkId, teacherId, sendParentOpenIdList);
        }
        logger.info("正在进行作业发送=>应发送的家长人数：" + totalParentCount + "；实际发送的家长人数：" + (totalParentCount - noSendParent));
        return Msg.success();
    }

    @ApiOperation(value = "获取某次作业的详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "作业id",dataType = "Integer",paramType = "query"),
    })
    @GetMapping(value = "/getHomeWorkDetail")
    public Msg getHomeWorkList(@RequestParam(value="id")Integer  homeworkId){
        HomeworkEntity homework = homeworkService.getHomeworkDetail(homeworkId);
        return Msg.success().add("homework", homework);

    }

    @ApiOperation(value = "老师：获取老师能够发送哪些班级的哪些科目的作业；家长：获取家长能够查看的孩子列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="uid",value = "用户id",dataType = "String",paramType = "query"),
    })
    @GetMapping(value = "/getSelectCondition")
    public Msg listClassOrStudentList(String uid){
        if ("".equals(uid) || uid == null){
            //uid为空的话，就是pc端的请求
            uid = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        //如果是教师的话，那么返回班级列表
        if (uid.startsWith("1")){
            Integer schoolCode = userService.getUserByUid(uid).getSchoolCode();
            List<CourseHomeworkEntity> courseList = homeworkService.listClassAndCourse(schoolCode, uid);
            return Msg.success().add("courseList", courseList);
        }
        //如果是家长的话，那么返回学生列表
        List<JSONObject> studentList = new ArrayList<>();
        if(uid.startsWith("3")){
            studentList = homeworkService.listStudentByParentId(uid);
        }
        return Msg.success().add("studentList", studentList);
    }


    @ApiOperation(value = "查询某个学生的作业列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="studentId",value = "学生id",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="currentPage",value = "当前页数",dataType = "Integer",paramType = "query"),
    })
    @GetMapping(value = "/getStudentHomeList")
    public Msg getStudentHomeList(Integer studentId, Integer currentPage){
        Integer total = homeworkService.countStudentReceiveHomework(studentId);
        // 小程序端一页默认显示5条数据
        PageHelper.startPage(currentPage, 5);
        List<HomeworkEntity> homeworkList = homeworkService.listStudentHomeworkInfo(studentId);
        return Msg.success().add("homeworkList", homeworkList).add("total",total);
    }


    @ApiOperation(value = "小程序端获取已发作业列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="uid",value = "用户id",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="classId",value = "班级id",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="courseId",value = "科目id",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="currentPage",value = "当前页数",dataType = "Integer",paramType = "query"),
    })
    @GetMapping(value = "/getHomeworkListForWeApp")
    public Msg getHomeworkListForWeApp(String uid, Integer classId, Integer courseId, Integer currentPage){
        Integer total = homeworkService.countTeacherSendHomework(uid,classId,courseId);
        //小程序端一页默认显示5条数据
        PageHelper.startPage(currentPage, 5);
        List<HomeworkEntity> homeworkList = homeworkService.listHomeworkInfo(uid, null, classId, courseId);
        return Msg.success().add("homeworkList", homeworkList).add("total", total);
    }


}



